package com.workerhelping.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.workerhelping.dto.AssistDTO;
import com.workerhelping.po.Income;
import com.workerhelping.po.IncomeCategory;
import com.workerhelping.result.Result;
import com.workerhelping.service.IncomeCategoryService;
import com.workerhelping.service.IncomeService;
import com.workerhelping.vo.IncomeVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/income")
public class IncomeController {

    @Autowired
    private IncomeService incomeService;

    @Autowired
    private IncomeCategoryService incomeCategoryService;

    /**
     * 保存收入信息
     *
     * @param incomeVO
     * @return
     */
    @PostMapping("/save")
    public Result<Integer> saveAndIncrease(@RequestBody IncomeVO incomeVO) {
        try {
            Income income = new Income();
            BeanUtils.copyProperties(incomeVO, income);
            Integer incomeId = incomeService.insertIncome(income);
            incomeCategoryService.updateMoneyById(income.getIcId(), income.getMoney());
            return Result.ok(incomeId);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail();
        }
    }


    /**
     * 发放补助后减少金额
     * @param assistDTO
     * @return
     */
    @PostMapping("/descIncome")
    public Result<String> descIncome(@RequestBody AssistDTO assistDTO) {
        try {
            Integer categoryId = assistDTO.getCategoryId();
            int count = assistDTO.getWorkerId().size();
            Double price = assistDTO.getPrice();
            IncomeCategory category = incomeCategoryService.getById(categoryId);
            double current = category.getCount();
            double remain = current - count * price;
            category.setCount(remain);
            incomeCategoryService.updateById(category);
            return Result.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail();
        }
    }

    /**
     * 分页查询
     * @param pageNo
     * @param pageSize
     * @return
     */
    @Deprecated
    @GetMapping("/findAll")
    public Result<Page<Income>> getAllIncome(@RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,
                                                @RequestParam(value = "pageSize", required = false, defaultValue = "6") Integer pageSize) {
        try {
            Page<Income> page = new Page<>(pageNo,pageSize);
            Page<Income> incomePage = incomeService.page(page);
            return Result.ok(incomePage);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail();
        }
    }
}
